import lib.arithmetics as arithmetics
import lib.problem as problem
import unittest

class Problem021(problem.Problem):
	def __init__(self):
		problem.Problem.__init__(self, 21)
		
	def d(self, n):
		return arithmetics.sum(arithmetics.divisors(n)[:-1])
	
	def areAmicable(self, a, b):
		da = self.d(a)
		db = self.d(b)
		
		return (not a == b) and da == b and db == a
	
	def allAmicablesUntil(self, n):
		amicables = []
		for a in range(1, n):
			b = self.d(a)
			
			if self.d(b) == a and (not a == b):
				if not a in amicables and not b in amicables:
					amicables.append(a)
					amicables.append(b)
						
		return amicables
				
	def sumAllAmicablesUntil(self, n):
		return arithmetics.sum(self.allAmicablesUntil(n))
		
	def solve(self):
		return self.sumAllAmicablesUntil(10000)
	
	
	
class Problem021Tester(unittest.TestCase):
	
	def setUp(self):
		self.p021 = Problem021()
		
	def testAreamicable220_284(self):
		self.assertTrue(self.p021.areAmicable(220, 284))
		
	def testAllAmicablesUntil300(self):
		amicables = self.p021.allAmicablesUntil(300)
		self.assertEquals([220, 284], amicables)
	
	def testSolve(self):
		self.assertEquals(31626, self.p021.solve())
